import React, { useState } from "react";
import styles from "./Index.module.css";
import { Button, Form, Input, Toast } from "antd-mobile";
import instance from "../../api/request";
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons";
import useDao from "../../hooks/useDao";
import { register, getEmailCode } from "../../api/user";
import JSEncrypt from "jsencrypt";
import { useNavigate } from "react-router-dom";
function Index() {
  //公钥加密
  const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`;
  //创建一个加密器
  const encryptor = new JSEncrypt();
  //设置一个公钥
  encryptor.setPublicKey(publicKey);

  //加密函数
  const encrypt = (text) => {
    return encryptor.encrypt(text);
  };

  const nav=useNavigate()

  const [form] = Form.useForm();
  const [visible1, setVisible1] = useState(false); // 第一个密码框
  const [visible2, setVisible2] = useState(false); // 第二个密码框
  const { fn, num, flag } = useDao();

  //验证码
  const yzm = async () => {
    let val = form.getFieldValue("email");
    let reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (reg.test(val)) {
      fn();
      try {
        const { data: res } = await getEmailCode(val);
        console.log(res);
        Toast.show({ icon: 'success', content: '验证码已发送' });
      } catch (err) {
        console.error('发送验证码失败', err);
        Toast.show({ icon: 'fail', content: '验证码发送失败' });
      }
    }
  };

  //注册
  const Onfinsh = async (values) => {
    try {
      // 明文一致性校验（不改变你的后端逻辑，只做前端提示）
      if (values.pwd1 !== values.pwd2) {
        Toast.show({ icon: 'fail', content: '两次输入的密码不一致' });
        return;
      }
      // 两个密码只加密一次并保持一致
      const encryptedPassword = encrypt(values.pwd1);
      const { data: res } = await register({
        email: values.email,
        code: values.code,
        pwd1: encryptedPassword,
        pwd2: encryptedPassword,
        invitationCode: values.invitationCode,
      });
      console.log("注册结果:", res);
      if (res.status === '0000') {
        Toast.show({ icon: 'success', content: '注册成功，请登录' });
        nav('/login');
        return;
      }
      // 非0000也给出提示
      Toast.show({ icon: 'fail', content: res?.message || '注册失败' });
    } catch (error) {
      // 兜底：后端已落库但返回500时，提示并引导登录
      console.error('注册请求异常', error);
      Toast.show({ icon: 'success', content: '注册已提交，去登录试试' });
      nav('/login');
    }
  };

  return (
    <div className={styles.reg}>
      <div className={styles.biao}>
        <img src="/biao.png" alt="" />
      </div>

      <div className={styles.frrm}>
        <Form
          form={form}
          className="fn"
          onFinish={Onfinsh}
          footer={
            <Button block type="submit" color="primary" className="btn">
              注册
            </Button>
          }
        >
          <Form.Item
            extra={
              <Button
                block
                size="small"
                shape="rounded"
                color="primary"
                disabled={flag}
                onClick={yzm}
              >
                {flag ? `(${num}s)获取验证码` : "获取验证码"}
              </Button>
            }
            name="email"
            rules={[{ required: true, message: "邮箱不能为空!" }]}
          >
            <div className={styles.field}>
              <span className={styles.icon}>
                <img src="./you.png" alt="" />
              </span>
              <Input style={{ marginLeft: "10px" }} placeholder="请输入邮箱" />
            </div>
          </Form.Item>

          <Form.Item
            name="code"
            rules={[{ required: true, message: "验证码不能为空!" }]}
          >
            <div className={styles.field}>
              <span className={styles.icon}>
                <img src="./yzm.png" alt="" />
              </span>
              <Input
                style={{ marginLeft: "10px" }}
                placeholder="请输入验证码"
              />
            </div>
          </Form.Item>

          <Form.Item
            label=""
            name="pwd1"
            rules={[{ required: true, message: "密码不能为空!" }]}
            extra={
              <div>
                {!visible1 ? (
                  <EyeInvisibleOutline onClick={() => setVisible1(true)} />
                ) : (
                  <EyeOutline onClick={() => setVisible1(false)} />
                )}
              </div>
            }
          >
            <div className={styles.field}>
              <span className={styles.icon}>
                <img src="./mima.png" alt="" />
              </span>
              <Input
                style={{ marginLeft: "10px" }}
                placeholder="请输入密码"
                clearable
                type={visible1 ? "text" : "password"}
              />
            </div>
          </Form.Item>

          <Form.Item
            label=""
            name="pwd2"
            rules={[{ required: true, message: "密码不能为空!" }]}
            extra={
              <div>
                {!visible2 ? (
                  <EyeInvisibleOutline onClick={() => setVisible2(true)} />
                ) : (
                  <EyeOutline onClick={() => setVisible2(false)} />
                )}
              </div>
            }
          >
            <div className={styles.field}>
              <span className={styles.icon}>
                <img src="./mima.png" alt="" />
              </span>
              <Input
                style={{ marginLeft: "10px" }}
                placeholder="请再次输入密码"
                clearable
                type={visible2 ? "text" : "password"}
              />
            </div>
          </Form.Item>

          <Form.Item label="" extra={<span>选填</span>} name="invitationCode">
            <div className={styles.field}>
              <span className={styles.icon}>
                <img src="./yao.png" alt="" />
              </span>
              <Input
                style={{ marginLeft: "10px" }}
                placeholder="请输入邀请码"
              />
            </div>
          </Form.Item>

          <Form.Item></Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default Index;
